import React from 'react';
import {
    Table,
    Space,
    Empty,
    Button,
    Tooltip,
    Dropdown,
    Typography,
    Menu
} from 'antd';
import {
    DownloadOutlined,
    DeleteOutlined,
    EllipsisOutlined,
    ArrowUpOutlined
} from '@ant-design/icons';
import FileIcon from '../../../../components/file/FileIcon';
import { FileItem, FileType, FileListProps } from '../types';
import styles from '../FileMgr.module.css';

const { Text } = Typography;

const FileList: React.FC<FileListProps> = ({
    files,
    loading,
    total,
    currentPage,
    pageSize,
    onPageChange,
    onFileSelect,
    selectedFiles,
    onPathChange,
    currentPath,
    onDownload
}) => {
    const formatFileSize = (size: number): string => {
        if (size < 1024) {
            return `${size} B`;
        } else if (size < 1024 * 1024) {
            return `${(size / 1024).toFixed(2)} KB`;
        } else if (size < 1024 * 1024 * 1024) {
            return `${(size / (1024 * 1024)).toFixed(2)} MB`;
        } else {
            return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
        }
    };

    const formatDate = (dateString: string): string => {
        const date = new Date(dateString);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    };

    const handleRowClick = (record: FileItem) => {
        if (record.isFolder) {
            const newPath = record.path.endsWith('/')
                ? record.path
                : `${record.path}/`;
            onPathChange(newPath);
        }
    };

    const handleParentFolderClick = () => {
        if (currentPath === '/' || !currentPath) return;

        const pathArray = currentPath.split('/').filter(Boolean);
        pathArray.pop();
        const parentPath = pathArray.length === 0 ? '/' : `/${pathArray.join('/')}/`;
        onPathChange(parentPath);
    };

    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            render: (text: string, record: FileItem) => (
                <div className={styles.fileNameCell}>
                    <FileIcon fileType={record.type} extension={record.extension} />
                    {record.isFolder ? (
                        <span
                            className={styles.folderName}
                            onClick={() => handleRowClick(record)}
                        >
                            {text}
                        </span>
                    ) : (
                        <span className={styles.fileName}>{text}</span>
                    )}
                </div>
            ),
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            render: (text: FileType, record: FileItem) => {
                if (record.isFolder) return '文件夹';

                const fileTypeMap: Record<FileType, string> = {
                    [FileType.ALL]: '所有',
                    [FileType.DOCUMENT]: '文档',
                    [FileType.IMAGE]: '图片',
                    [FileType.AUDIO]: '音频',
                    [FileType.VIDEO]: '视频',
                    [FileType.FOLDER]: '文件夹',
                    [FileType.ARCHIVE]: '压缩包',
                    [FileType.OTHER]: '其他'
                };

                return fileTypeMap[text] || '未知';
            }
        },
        {
            title: '大小',
            dataIndex: 'size',
            key: 'size',
            width: 120,
            render: (size: number, record: FileItem) => (
                <span className={styles.fileSize}>
                    {record.isFolder ? '-' : formatFileSize(size)}
                </span>
            ),
        },
        {
            title: '更新时间',
            dataIndex: 'updatedAt',
            key: 'updatedAt',
            width: 180,
            render: (date: string) => (
                <span className={styles.fileDate}>{formatDate(date)}</span>
            ),
        },
        {
            title: '操作',
            key: 'action',
            width: 120,
            render: (_, record: FileItem) => (
                <Space size="middle">
                    {!record.isFolder && (
                        <Tooltip title="下载">
                            <Button
                                type="text"
                                size="small"
                                icon={<DownloadOutlined />}
                                onClick={(e) => {
                                    e.stopPropagation();
                                    onDownload(record.id);
                                }}
                            />
                        </Tooltip>
                    )}
                    <Dropdown
                        menu={{
                            items: [
                                {
                                    key: 'download',
                                    label: '下载',
                                    icon: <DownloadOutlined />,
                                    disabled: record.isFolder,
                                    onClick: (e) => {
                                        e.domEvent.stopPropagation();
                                        onDownload(record.id);
                                    }
                                },
                                {
                                    key: 'delete',
                                    label: '删除',
                                    icon: <DeleteOutlined />,
                                    danger: true,
                                    onClick: (e) => {
                                        e.domEvent.stopPropagation();
                                        onFileSelect([record.id]);
                                    }
                                }
                            ]
                        }}
                        trigger={['click']}
                    >
                        <Button
                            type="text"
                            size="small"
                            icon={<EllipsisOutlined />}
                            onClick={(e) => e.stopPropagation()}
                        />
                    </Dropdown>
                </Space>
            ),
        },
    ];

    // 添加"返回上级"行
    const dataSource = currentPath !== '/'
        ? [
            {
                id: 'parent-folder',
                name: '..',
                path: '',
                type: FileType.FOLDER,
                size: 0,
                mimeType: '',
                extension: '',
                isFolder: true,
                createdAt: '',
                updatedAt: '',
                __isParentFolder: true
            } as FileItem,
            ...files
        ]
        : files;

    return (
        <div className={styles.fileListContainer}>
            <Table
                className={styles.fileTable}
                dataSource={dataSource}
                columns={columns}
                rowKey="id"
                loading={loading}
                pagination={{
                    current: currentPage,
                    pageSize: pageSize,
                    total: total,
                    onChange: onPageChange,
                    showSizeChanger: true,
                    showTotal: (total) => `共 ${total} 项`,
                    className: styles.pagination
                }}
                rowSelection={{
                    type: 'checkbox',
                    selectedRowKeys: selectedFiles,
                    onChange: onFileSelect,
                    getCheckboxProps: (record) => ({
                        disabled: (record as any)?.__isParentFolder,
                    }),
                }}
                onRow={(record) => ({
                    onClick: () => {
                        if ((record as any)?.__isParentFolder) {
                            handleParentFolderClick();
                            return;
                        }
                        if (record.isFolder) {
                            handleRowClick(record);
                        }
                    },
                    style: { cursor: record.isFolder ? 'pointer' : 'default' }
                })}
                locale={{
                    emptyText: (
                        <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description="暂无文件"
                        />
                    )
                }}
            />
        </div>
    );
};

export default FileList; 